package com.lottery.controller;

import com.lottery.dto.LotteryResult;
import com.lottery.entity.LotteryRecord;
import com.lottery.entity.Prize;
import com.lottery.entity.User;
import com.lottery.entity.UserChance;
import com.lottery.service.LotteryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/lottery")
@CrossOrigin(origins = "*")
public class LotteryController {

    @Autowired
    private LotteryService lotteryService;

    /**
     * 执行抽奖
     */
    @PostMapping("/draw")
    public ResponseEntity<?> drawLottery(Authentication authentication) {
        try {
            User user = (User) authentication.getPrincipal();
            LotteryRecord record = lotteryService.drawLottery(user.getId());
            
            // 获取用户剩余抽奖次数
            UserChance userChance = lotteryService.getUserChance(user.getId());
            
            // 构建返回结果
            LotteryResult result = new LotteryResult();
            result.setId(record.getId());
            result.setPrizeName(record.getPrizeName());
            result.setWinner(record.getIsWinner());
            result.setDrawTime(record.getCreatedAt());
            result.setRemainingChances(userChance.getChances());
            
            // 如果中奖，获取奖品信息
            if (record.getIsWinner() && record.getPrizeId() != null) {
                Prize prize = lotteryService.getPrizeById(record.getPrizeId());
                if (prize != null) {
                    result.setPrizeDescription(prize.getDescription());
                    result.setPrizeImageUrl(prize.getImageUrl());
                }
            }
            
            return ResponseEntity.ok(result);
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取用户抽奖次数
     */
    @GetMapping("/chances")
    public ResponseEntity<?> getUserChances(Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        UserChance userChance = lotteryService.getUserChance(user.getId());
        
        Map<String, Object> response = new HashMap<>();
        response.put("chances", userChance.getChances());
        response.put("updatedAt", userChance.getUpdatedAt());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户抽奖记录
     */
    @GetMapping("/records")
    public ResponseEntity<?> getUserRecords(Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        List<LotteryRecord> records = lotteryService.getUserLotteryRecords(user.getId());
        
        return ResponseEntity.ok(records);
    }

    /**
     * 获取所有奖品信息（用于转盘显示）
     */
    @GetMapping("/prizes")
    public ResponseEntity<?> getAllPrizes() {
        List<Prize> prizes = lotteryService.getAllPrizes();
        return ResponseEntity.ok(prizes);
    }

    /**
     * 获取可用奖品信息
     */
    @GetMapping("/prizes/available")
    public ResponseEntity<?> getAvailablePrizes() {
        List<Prize> prizes = lotteryService.getAvailablePrizes();
        return ResponseEntity.ok(prizes);
    }
}